package com.bizmda.bizsip.sample.source.listener;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.bizmda.bizsip.common.BizException;
import com.bizmda.bizsip.common.BizMessage;
import com.bizmda.bizsip.sample.source.longtcpnetty.NettyClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.nio.charset.StandardCharsets;

/**
 * RabbitMQ接收服务
 * @author shizhengye
 */
@Slf4j
@Service
public class LongTcpSourceSampleListener {
    @Autowired
    private NettyClient nettyClient;

    @RabbitListener(queuesToDeclare = @Queue(value = "queue.bizsip.longtcp", durable = "true", autoDelete = "false"))
    public void onMessage(Message message) {
        try {
            this.process(message);
        } catch (Exception e) {
            log.error("Netty客户端侦听器出错!",e);
        }
    }

    private void process(Message message) throws BizException {
        JSONObject jsonObject;
        JSONObject data;
        String str = new String(message.getBody(), StandardCharsets.UTF_8);
        jsonObject = JSONUtil.parseObj(str);
        BizMessage<JSONObject> bizMessage = new BizMessage<>(jsonObject);
        if (bizMessage.getCode() != 0) {
            log.error("错误:{},{}", bizMessage.getCode(), bizMessage.getMessage());
            return;
        }
        data = bizMessage.getData();

        this.nettyClient.sendData(JSONUtil.toJsonStr(data).getBytes(StandardCharsets.UTF_8));
    }
}
